package online.flowerinsnow.minecraft.bukkit.floweress.command

import online.flowerinsnow.minecraft.bukkit.floweress.message.MessageConfig
import online.flowerinsnow.minecraft.bukkit.floweress.util.CommandUtils
import org.bukkit.Bukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
import org.bukkit.command.TabExecutor
import org.bukkit.entity.Player

class FlyCommand : TabExecutor {
    override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
        when (args.size) {
            0 -> {
                if (CommandUtils.checkPermissionAndConsole(sender, "floweress.fly.self")) return true
                val player = sender as Player
                val b = player.allowFlight
                if (b) {
                    player.sendMessage(MessageConfig.FLY_DISABLE_SELF.getMessage())
                } else {
                    player.sendMessage(MessageConfig.FLY_ENABLE_SELF.getMessage())
                }
                player.allowFlight = !b
            }
            1 -> {
                if (CommandUtils.checkPermission(sender, "floweress.fly.other")) return true
                val player = Bukkit.getPlayerExact(args[0])
                if (player == null) {
                    sender.sendMessage(MessageConfig.TARGETNOTONLINE.getMessage())
                    return true
                }
                val b = player.allowFlight
                if (b) {
                    sender.sendMessage(MessageConfig.FLY_DISABLE_OTHER.getMessage()
                            .replace("%(PLAYER)", player.name))
                } else {
                    sender.sendMessage(MessageConfig.FLY_ENABLE_SELF.getMessage()
                            .replace("%(PLAYER)", player.name))
                }
                player.allowFlight = !b
            }
            else -> {
                sendUsage(sender)
            }
        }
        return true
    }

    override fun onTabComplete(sender: CommandSender, command: Command, alias: String, args: Array<out String>): MutableList<String> {
        if (!sender.hasPermission("floweress.fly.other") || args.size != 1) {
            return ArrayList()
        }
        val list = ArrayList<String>()
        Bukkit.getOnlinePlayers().forEach { p -> list.add(p.name) }
        list.removeIf { s -> !s.startsWith(args[0], true) }
        return list
    }

    private fun sendUsage(sender: CommandSender) {
        sender.sendMessage(MessageConfig.FLY_USAGE.getMessage())
    }

}